package guda.house.biz.util;

import guda.grape.util.Convert;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.util.StringUtils;

/**
 * Created by well on 15/11/9.
 */
public class ArrayUtil {

    public static final String DEFAULT_SPLIT_CHAR = ",";

    public static final String[] EMPTY_STRING_ARRAY = new String[0];

    public static String array2String(String[] array){
        return array2String(array, DEFAULT_SPLIT_CHAR);
    }

    public static String array2String(String[] array, String splitChar){
        if(array == null || array.length == 0){
            return null;
        }
        StringBuilder buf = new StringBuilder();
        for(String s:array){
            if(StringUtils.hasText(s)) {
                buf.append(s).append(splitChar);
            }
        }
        if(buf.length()>0){
            return buf.substring(0,buf.length()-1);
        }
        return buf.toString();
    }

    public static boolean inArray(Object checkObj,Object array){
        if(checkObj == null || array == null){
            return false;
        }
        Object[] a =null;
        if(array instanceof String){
            a = ((String) array).split(",");
        }
        if(array.getClass().isArray()){
            a  = (Object[])array;
        }
        if(a == null){
            return false;
        }
        if(a.length == 0){
            return false;
        }
        for(Object o:a){
            if(o == null){
                continue;
            }
            if(String.valueOf(o).equals(String.valueOf(checkObj))){
                return true;
            }
        }
        return false;
    }

    public static String[] string2Array(String s){
        return string2Array(s, DEFAULT_SPLIT_CHAR);

    }

    public static String[] string2Array(String s,String splitChar){
        if(s == null){
            return EMPTY_STRING_ARRAY;
        }
        return s.split(splitChar);

    }

    public static String index(Object str,Object index){
        if(str == null || index == null){
            return null;
        }
        int i = Convert.toInt(index);
        String[] split = str.toString().split(DEFAULT_SPLIT_CHAR);
        if(split.length>i){
            return split[i];
        }
        return null;

    }
}
